package edu.scau.mis.pos.service.impl;

import edu.scau.mis.core.utils.DateUtils;
import edu.scau.mis.pos.entity.OrderItem;
import edu.scau.mis.pos.entity.PosCategory;
import edu.scau.mis.pos.entity.PosItem;
import edu.scau.mis.pos.entity.PosOrder;
import edu.scau.mis.pos.mapper.CategoryMapper;
import edu.scau.mis.pos.mapper.OrderItemMapper;
import edu.scau.mis.pos.mapper.PosItemMapper;
import edu.scau.mis.pos.mapper.PosOrderMapper;
import edu.scau.mis.pos.service.IOrderItemService;
import edu.scau.mis.pos.vo.OrderItemVo;
import edu.scau.mis.pos.vo.DashboardVo;
import edu.scau.mis.pos.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 订单明细表(OrderItem)表服务实现类
 *
 * @author CJW
 * @since 2021-11-08 21:26:35
 */
@Service("orderItemService")
public class OrderItemServiceImpl implements IOrderItemService {
    @Autowired
    private OrderItemMapper orderItemMapper;
    Map<String,List<OrderItem>> mapCache = new HashMap<>(); //缓存数据
    @Autowired
    private PosOrderMapper orderMapper;

    @Autowired
    private PosItemMapper posItemMapper;
    @Autowired
    private CategoryMapper categoryMapper;



    /**
     * 通过ID查询单条数据
     *
     * @param orderItemId 主键
     * @return 实例对象
     */
    @Override
    public OrderItem queryById(Integer orderItemId) {

        return this.orderItemMapper.queryById(orderItemId);
    }

    /**
     * 查询指定行
     *
     * @param orderItem 筛选条件
     * @return 查询结果
     */
    @Override
    public List<OrderItem> queryAll(OrderItem orderItem) {

        return this.orderItemMapper.queryAll(orderItem);
    }


    /**
     * 新增数据
     *
     * @param orderItem 实例对象
     * @return 实例对象
     */
    @Override
    public OrderItem insert(OrderItem orderItem) {
        this.orderItemMapper.insert(orderItem);
        return orderItem;
    }

    /**
     * 修改数据
     *
     * @param orderItem 实例对象
     * @return 实例对象
     */
    @Override
    public OrderItem update(OrderItem orderItem) {
        this.orderItemMapper.update(orderItem);
        return this.queryById(orderItem.getOrderItemId());
    }

    /**
     * 通过主键删除数据
     *
     * @param orderItemId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer orderItemId) {

        return this.orderItemMapper.deleteById(orderItemId) > 0;
    }

    /**
     * 步骤1：根据读者证号查询读者信息和业务关键信息
     *
     * @param orderNo 读者证号
     * @return 读者信息，借阅中图书数量，超期未还数
     */
    @Override
    public Map<String, Object> getOrderAndBusinessInformationByOrderNo(String orderNo) {
        this.createMapCache(orderNo);  // 创建借阅数据缓存
        Map<String, Object> info = new HashMap<String,Object>();
        PosOrder posOrder = this.orderMapper.queryOrderWithItemListByOrderNo(orderNo);
        int orderId = posOrder.getOrderId();
//        int quantity = this.orderItemMapper.sumOrderItemQuantity(orderId);
        info.put("order",posOrder);
        //info.put("quantity",quantity);
//        info.put("quantity",quantity);
        return info;
    }

    /**
     * 生成缓存数据_内存存储_HashMap
     * 步骤1_依赖方法1
     * @param orderNo
     * @return
     */

    private Map<String, List<OrderItem>> createMapCache(String orderNo){
        List<OrderItem> orderItemList = new ArrayList<>();
        mapCache.put(orderNo,orderItemList);
        return mapCache;
    }

    /**
     * 得到借阅中图书列表
     * 步骤1_依赖方法2
     * @param orderNo
     * @return
     */
    private List<PosItem> getAddingItemOfOrder(String orderNo){
        PosOrder posOrder = this.orderMapper.queryOrderWithItemListByOrderNo(orderNo);
        return posOrder.getItemList();

    }

    /**
     * 步骤2：添加图书到待借图书列表
     * @param orderItemVo 传值对象
     * 封装了orderNo和itemNo
     * @return 待借图书列表
     */
    @Override
    public List<PosItem> enterLineOrderItem(OrderItemVo orderItemVo) {
        String orderNo = orderItemVo.getOrderNo();
        int orderId = this.orderMapper.queryIdByOrderNo(orderNo).getOrderId();
        PosItem posItem = this.posItemMapper.queryItemByItemNo(orderItemVo.getItemNo());
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(orderId);
        orderItem.setItemId(posItem.getItemId());
        orderItem.setSalePrice(posItem.getPrice()*orderItemVo.getQuantity());
        orderItem.setQuantity(orderItemVo.getQuantity());

        int  itemQuantity = orderItemVo.getQuantity();
        int oldQuantity = posItem.getInventory();
        posItem.setInventory(oldQuantity-itemQuantity);
        posItemMapper.update(posItem);
        List<OrderItem> orderItemList = mapCache.get(orderNo);
        orderItemList.add(orderItem);
        mapCache.put(orderNo,orderItemList);
        return this.getEnterItemList(orderNo);
    }


    /**
     * 根据orderNo从缓存加载itemIds，得到待借图书集合
     * 步骤2_依赖方法2
     * @param orderNo 读者证号
     * @return 待借图书集合
     */
    private List<PosItem> getEnterItemList(String orderNo){
        List<PosItem> enterItemList = new ArrayList<>();
        List<OrderItem> orderItemList = mapCache.get(orderNo);
        for(OrderItem orderItem : orderItemList){
            enterItemList.add(this.posItemMapper.queryById(orderItem.getItemId()));
        }
        return enterItemList;
    }


    /**
     * 步骤3：确认借书
     * @param orderNo 读者证号
     */
    @Override
    public boolean ConfirmAddItem(String orderNo) {
        boolean flag = false;
        List<OrderItem> orderItemList = mapCache.get(orderNo);
        int availableQuantity = 10 - getAddingItemOfOrder(orderNo).size();
        int quantity = orderItemList.size();
        if(quantity > 0 && quantity <= availableQuantity){
            flag = this.orderItemMapper.insertBatch(orderItemList) > 0;
            PosOrder posOrder = this.orderMapper.queryIdByOrderNo(orderNo);
            Date date = DateUtils.getNowDate();
            Integer totalQuantity = this.orderMapper.queryOrderItemQuantity(orderNo);
            Double totalAmount = this.orderMapper.queryOrderItemAmount(orderNo);
            posOrder.setTotalquantity(totalQuantity);
            posOrder.setTotalamount(totalAmount);
            posOrder.setSaleDatetime(date.toString());
            orderMapper.update(posOrder);
            this.removeMapCache(orderNo);
        }
        return flag;
    }



    /**
     * 删除缓存数据_内存存储_HashMap
     * 步骤3_依赖方法1
     * @param orderNo
     */
    private void removeMapCache(String orderNo) {
        Iterator<Map.Entry<String,List<OrderItem>>> iterator = mapCache.entrySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().getKey();
            if (orderNo.equals(key)) {
                iterator.remove();
            }
        }
    }

    /**
     * 按图书类别id统计借阅数
     * @return 记录数
     */
    @Override
    public List<DashboardVo> CountByCategoryId(){
        List<PosCategory> categoryList = this.categoryMapper.queryAll(new PosCategory());
        List<DashboardVo> dashboardVoList = new ArrayList<>();
        for(PosCategory posCategory : categoryList){
            DashboardVo dashboardVo = new DashboardVo();
            long count = this.orderItemMapper.countByCategoryId(posCategory.getCategoryId());
            String name = posCategory.getCategoryName();
            dashboardVo.setValue(count);
            dashboardVo.setName(name);
            dashboardVoList.add(dashboardVo);
        }
        return dashboardVoList;
    }

}

